import cv2  
import numpy as np  
import pandas as pd
import time
xs,ys,ws,hs = 0,0,0,0  #selection.x selection.y  
xo,yo=0,0 #origin.x origin.y  
selectObject = False  
trackObject = 0  
hp = True
filt = 'WF'
threshold = 0.6
def onMouse(event, x, y, flags, prams):   
    global xs,ys,ws,hs,selectObject,xo,yo,trackObject  
    if selectObject == True:  
        xs = min(x, xo)  
        ys = min(y, yo)  
        ws = abs(x-xo)  
        hs = abs(y-yo)  
    if event == cv2.EVENT_LBUTTONDOWN:  
        print('down')
        xo,yo = x, y  
        xs,ys,ws,hs= x, y, 0, 0  
        selectObject = True  
    elif event == cv2.EVENT_LBUTTONUP:  
        print('up')
        selectObject = False  
        trackObject = -1  

def WeightFilter(rects, weights, threshold = 0.7):
    if len(rects) <= 0:
        print("未检测到人体，", rects)
        return rects
    recW = np.hstack((rects, weights))
    #print(rects, weights)
    dfRecW = pd.DataFrame(recW, columns=('xA', 'yA', 'xB', 'yB', 'weights'))
    dfRecW = dfRecW.sort_values(by='weights', ascending=False)
    pick = np.int32(dfRecW[dfRecW.weights > threshold])
    if pick.size >= 1:
        return tuple(pick[:,:4])
    else :
        return []
 
# cap = cv2.VideoCapture("rtsp://admin:admin12345@192.168.1.230:554/h264/ch36/main/av_stream")  
cap = cv2.VideoCapture("E:\\py\\camHumDetect\\img\\bd1627e63900eb94db93cab16e0cd5bc.mp4")
ret,frame = cap.read()  

#hog
hog = cv2.HOGDescriptor()
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())

cv2.namedWindow('imshow')  
#cv2.setMouseCallback('imshow',onMouse)  
term_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 )  
while(True):  
    ret,frame = cap.read()  
    hsv =  cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)  
    mask = cv2.inRange(hsv, np.array((0., 30.,10.)), np.array((180.,256.,255.))) 
    
    if hp == True:
        (rects, weights) = hog.detectMultiScale(hsv, winStride=(4, 4), padding=(8, 8), scale=1.08)
        rects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in rects])
        print("检测到人体：", len(rects))
        if len(rects) > 0:
            pick = WeightFilter(rects, weights, threshold)
            print(pick)
            for (xA, yA, xB, yB) in pick:
                # cv2.rectangle(hsv, (xA, yA), (xB, yB), (0, 255, 0), 2)
                xs = min(xA, xB)  
                ys = min(yA, yB)
                ws = abs(xA-xB)  
                hs = abs(yA-yB)  
            hp = False
            cv2.imshow('hsv_roi',hsv[ys:ys+hs, xs:xs+ws])
            selectObject = False  
            trackObject = -1
            
    if trackObject != 0:  
        if trackObject == -1:  
            track_window=(xs,ys,ws,hs)  
            maskroi = mask[ys:ys+hs, xs:xs+ws]  
            hsv_roi = hsv[ys:ys+hs, xs:xs+ws]  
            roi_hist = cv2.calcHist([hsv_roi],[0],maskroi,[180],[0,180])  
            cv2.normalize(roi_hist,roi_hist,0,255,cv2.NORM_MINMAX)  
            trackObject = 1  
        dst = cv2.calcBackProject([hsv], [0], roi_hist, [0, 180], 1)  
        dst &= mask  
        ret, track_window = cv2.CamShift(dst, track_window, term_crit)  
        pts = cv2.boxPoints(ret)  
        pts = np.int0(pts)  
        img2 = cv2.polylines(frame,[pts],True, 255,2)
        #cv2.imshow('hsv_roi',hsv[ys:ys+hs, xs:xs+ws])
        #print(roi_hist)    
    
    if selectObject == True and ws>0 and hs>0:  
        cv2.imshow('imshow1',frame[ys:ys+hs,xs:xs+ws])  
        cv2.bitwise_not(frame[ys:ys+hs,xs:xs+ws],frame[ys:ys+hs,xs:xs+ws])  
    cv2.imshow('imshow',frame) 
    if  cv2.waitKey(10)==27:  
        break  

cv2.destroyAllWindows()  
